<script lang="tsx">
import {defineComponent, nextTick, onMounted, ref, watch} from "vue";
import {ElTreeSelect} from "element-plus"
import {SelectOrgProps, selectOrgProps} from "/@/components/Business/SelectOrg/ts";
import {listTreeOrg} from "/@/api/system/OrgApi";
import {useUserStore} from "/@/store/modules/user";
import BaseIcon from '/@/components/Base/BaseIcon/index.vue'
export default defineComponent({
  name: "SelectOrg",
  props: selectOrgProps,
  setup(props: SelectOrgProps, {expose, emit, slots}) {
    const options = ref<any[]>([])
    const propsParams = {
      label: 'orgName',
      children: 'children',
      disabled: ''

    }
    const value = ref()
    watch(
        () => props.modelValue,
        (newValue) => {
          value.value = newValue
        },
        {deep: true, immediate: true}
    );
    watch(
        () => value.value,
        (newValue) => {
          emit("update:modelValue", newValue)
        },
        {deep: true, immediate: true}
    );
    const initOrgList = async () => {
      let orgId = "0"
      if (props.scope === 'current') {
        let userStore = useUserStore();
        orgId = userStore.orgId
      }
      options.value = await listTreeOrg({isCompany: props.isCompany, orgId})
    }
    onMounted(() => {
      initOrgList()
    })

    const render = () => {
      if (props.enabledSwitch) {
        propsParams.disabled = 'disabled'
      }
      let keys = [] as any[]
      if (props.modelValue) {
        if (props.modelValue instanceof Array) {
          keys = props.modelValue
        } else {
          keys = [props.modelValue]
        }
      }


      return <ElTreeSelect multiple={props.multiple} show-checkbox={props.multiple} v-model={value.value} check-strictly={true} default-expanded-keys={keys} class="w-full"
                           node-key="orgId" props={propsParams} data={options.value}>
        {{
          default: ({ node, data })=> {
            if (data.type == 1) {
              return <div class="flex">
                <BaseIcon icon="bjx-gongsi" class="mr-1.5"></BaseIcon>
                <span>{data.name}</span>
              </div>
            } else {
              return  <div class="flex">
                <BaseIcon icon="bjx-bumenguanli" class="mr-1.5"></BaseIcon>
                <span>{data.name}</span>
              </div>
            }
          }

        }}
      </ElTreeSelect>
    }
    return render
  }
})
</script>

<style scoped>

</style>